package com.qf.controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

/**
 * 上传图片或文件
 * @author lixu
 */
@Controller
public class UploadController {

    /**
     * 上传文件  请求体传文件或图片
     * <form action="/upload" method="post" enctype="multipart/form-data">
     *     上传图片：<input type="file" name="file"><br/>
     *     <input type="submit" value="上传">
     * </form>
     */
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {

        String realPath = request.getSession().getServletContext().getRealPath("/upload/");


        System.out.println("文件的原始名：" + file.getOriginalFilename());
        //扩展名
        String ext1 = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        System.out.println("手写获取的扩展名:" + ext1);
        //工具
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        //文件名
        // uuid
        // 时间戳  142131414414241124
        String fileName = String.valueOf(System.currentTimeMillis());
        fileName += String.valueOf(new Random().nextInt(1000));
        //文件的真实路径
        String url = realPath + fileName + "." + ext;
        //传送文件到指定的URL这个位置上

        File file1 = new File(realPath);
        if(!file1.exists()){
            file1.mkdirs();
        }
        file.transferTo(new File(url));

        return "success/success";
    }
    /**
     * 下载   附件
     *
     *  Rest风格开发
     */
    @RequestMapping("/download")
    public void downloadFile(String fileName,
                             HttpServletRequest request,
                             HttpServletResponse response) throws Exception{
        //1:真实路径
        String realPath = request.getSession().getServletContext().getRealPath("/upload/");
        //2:绝对路径
        InputStream inputStream = new FileInputStream(realPath + fileName);
        //3:设置响应头信息  让浏览器知道此流是附件 浏览器才会使用下载方式进行下载
        //attachment:附件 filename
        response.addHeader("content-disposition","attachment;filename="+fileName);
        //4:响应流 负责将图片传送到页面进行下载
        ServletOutputStream outputStream = response.getOutputStream();
        //5:流转换工具类
        IOUtils.copy(inputStream,outputStream);
    }
}
